package cn.trda.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.trda.constants.WebConstants;
import cn.trda.pojo.FunctionExt;
import cn.trda.pojo.Role;
import cn.trda.pojo.RolePremission;
import cn.trda.pojo.User;
import cn.trda.service.FunctionService;
import cn.trda.service.PermissionService;
import cn.trda.service.RoleService;

@Controller
@RequestMapping("permission")
public class PermissionController extends BaseController{
	private static final Logger logger = Logger.getLogger(PermissionController.class);
	@Autowired
	private RoleService roleservice;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private FunctionService functionService;
	@RequestMapping("/manage")
	public String tomanage(Model model){
		List<Role> roles = roleservice.selectAll(null);
		model.addAttribute("roles", roles);
		return "permission_manage";
	}
	@RequestMapping("/list/{roleid}")
	@ResponseBody
	public Map<String,Object> getlist(@PathVariable("roleid")Long roleid){
		Map<String,Object> map = new HashMap<String,Object>();
		List<FunctionExt> functions = functionService.selectAllFunctions();
		//恢复原来的状态，由于使用了缓存，清除上次的影响
				for (int i = 0; i < functions.size(); i++) {
					functions.get(i).setChecked("unchecked");
					functions.get(i).setChildren(new ArrayList<FunctionExt>());
				}			
				// 得到权限根据角色id
				List<RolePremission> permissions = permissionService.selectByRoleid(roleid);
				// 根据权限给功能对象赋值选中状态
				for (RolePremission permission : permissions) {
					for (int i = 0; i < functions.size(); i++) {
						if (permission.getFunctionid() == functions.get(i).getId()) {
							functions.get(i).setChecked("checked");
							break;
						}
					}
				}
				//转化成EasyUITreeGridRows集合
				List<FunctionExt> rows = new ArrayList<FunctionExt>();
				//从根节点开始加载
				functionsToEasyUITreeGridRows(functions,rows,0L);
				//分页
				map.put("total", null);
				map.put("rows", rows);
				return map;
		
		
	}
	public void functionsToEasyUITreeGridRows(List<FunctionExt> functions,List<FunctionExt> rows, Long parentid) {
		for (int i = 0; i < functions.size(); i++) {
			FunctionExt row = null;
			if ((long)functions.get(i).getParentid() == parentid) {
				//父目录
				row = functions.get(i);
				// 子目录
				functionsToEasyUITreeGridRows(functions, row.getChildren(),
						functions.get(i).getId());
				rows.add(row);
			}
		}
	}
	@RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public String update(String flist,HttpSession session,RolePremission pm) throws Exception{
		if (logger.isDebugEnabled()) {
			logger.debug("permission/update,传入的function ids: " + flist);
		}
		pm.setId(null);
		User user = this.getSessionUser(session);
		pm.setCreatedby(user.getUsercode());
		pm.setCreationtime(new Date());
		pm.setIsstart(1);
		if (pm.getRoleid() == null) {
			throw new Exception("删除角色权限时，roleid为null值！！");
		}
		permissionService.tx_delAddPremission(pm, flist);
		// 添加日志记录
		this.addLog(user, "用户修改角色ID：" + pm.getRoleid() + " 的对应的功能ID为：" +
		flist);
		return WebConstants.OPERATION_MESSAGE_SUCCESS;
	}
}
